using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TradeFlow.Server.Dto;
using TradeFlow.Server.Models;
using SqlSugar;
using TradeFlow.Server.Language;

namespace TradeFlow.Server.Service
{
    /// <summary>
    /// 库存服务类
    /// </summary>
    public class JxStockService : IApplicationService
    {
        private readonly SugarRepository<JxGoods> _goodsRepository;
        private readonly SugarRepository<JxBillHead> _billHeadRepository;
        private readonly SugarRepository<JxBillList> _billListRepository;

        /// <summary>
        /// 根据商品代码和单据类型计算数量
        /// </summary>
        /// <param name="goodsCode"></param>
        /// <param name="billType"></param>
        /// <returns></returns>
        private async Task<int> CalculateBillQuantityAsync(string goodsCode, string billType)
        {
            // 根据不同的单据类型进行查询
            var typeMap = new Dictionary<string, string>()
            {
                { "Purchase", BillType.Import },
                { "PurchaseReturn", BillType.ImportReturn },
                { "Sale", BillType.Export },
                { "SaleReturn", BillType.ExportReturn }
            };

            if (!typeMap.ContainsKey(billType))
                return 0;

            // 由于JxBillList.Code是string类型，直接进行字符串比较
            var totalQuantity = await _billListRepository.AsQueryable()
                .LeftJoin<JxBillHead>((list, head) => list.HeadId == head.Id)
                .Where((list, head) => 
                    list.Code == goodsCode && 
                    head.Type == typeMap[billType] &&
                    head.Status != "作废")
                .SumAsync(list => list.Qty ?? 0);

            return totalQuantity;
        }

        /// <summary>
        /// 分页查询库存信息（实现与JxcLite一致的功能）
        /// </summary>
        /// <param name="pageNo"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<PageResult<InventoryInfo>> QueryInventoriesAsync(int pageNo, int pageSize)
        {
            // 获取所有商品的基础信息
            var goodsQuery = _goodsRepository.AsQueryable();
            var goodsList = await goodsQuery.ToListAsync();

            // 构建库存信息列表
            var inventoryList = new List<InventoryInfo>();
            foreach (var goods in goodsList)
            {
                // 计算各种数量
                var importQty = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "Purchase");
                var importReturnQty = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "PurchaseReturn");
                var exportQty = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "Sale");
                var exportReturnQty = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "SaleReturn");
                var inventoryQty = importQty - importReturnQty - exportQty + exportReturnQty;

                string codeStr = Convert.ToString(goods.Code);
                inventoryList.Add(new InventoryInfo
                {
                    Id = goods.Id,
                    Code = codeStr,
                    Name = goods.Name,
                    Category = goods.Category,
                    Model = goods.Model,
                    Producer = goods.Producer,
                    Unit = goods.Unit,
                    BuyPrice = goods.BuyPrice,
                    SalePrice = goods.SalePrice,
                    SafeQty = goods.SafeQty,
                    ImportQty = importQty,
                    ImportReturnQty = importReturnQty,
                    ExportQty = exportQty,
                    ExportReturnQty = exportReturnQty,
                    InventoryQty = inventoryQty
                });
            }

            // 分页处理
            var totalCount = inventoryList.Count;
            var items = inventoryList.Skip((pageNo - 1) * pageSize).Take(pageSize).ToList();

            // 由于PageResult的具体实现不清楚，我们暂时返回NotImplementedException
            throw new NotImplementedException("需要调整接口返回类型，PageResult的实现不清楚");
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="goodsRepository"></param>
        /// <param name="billHeadRepository"></param>
        /// <param name="billListRepository"></param>
        /// <param name="localizer"></param>
        public JxStockService(SugarRepository<JxGoods> goodsRepository, SugarRepository<JxBillHead> billHeadRepository, SugarRepository<JxBillList> billListRepository )
        {
            _goodsRepository = goodsRepository;
            _billHeadRepository = billHeadRepository;
            _billListRepository = billListRepository;
        }

        /// <summary>
        /// 获取商品库存列表
        /// </summary>
        /// <returns></returns>
        public async Task<RestfulResult<List<JxStockInfo>>> GetStockListAsync()
        {
            try
            {
                // 获取所有商品
                var goodsList = await _goodsRepository.AsQueryable().ToListAsync();
                
                var stockList = new List<JxStockInfo>();
                
                foreach (var goods in goodsList)
                {
                    // 计算进货数量
                    var purchaseQuantity = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "Purchase");
                    // 计算进退货数量
                    var purchaseReturnQuantity = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "PurchaseReturn");
                    // 计算销货数量
                    var saleQuantity = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "Sale");
                    // 计算销退货数量
                    var saleReturnQuantity = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "SaleReturn");
                    
                    // 计算当前库存
                    var currentStock = purchaseQuantity - purchaseReturnQuantity - saleQuantity + saleReturnQuantity;
                    
                    // 判断是否低于安全库存
                    bool belowSafetyStock = goods.SafeQty > 0 && currentStock < goods.SafeQty;
                    
                    stockList.Add(new JxStockInfo
                    {
                        GoodsCode = Convert.ToString(goods.Code),
                        GoodsName = goods.Name,
                        GoodsCategory = goods.Category,
                        Specifications = goods.Model,
                        Origin = goods.Producer,
                        Unit = goods.Unit,
                        SafetyStock = goods.SafeQty ?? 0,
                        PurchaseQuantity = purchaseQuantity,
                        PurchaseReturnQuantity = purchaseReturnQuantity,
                        SaleQuantity = saleQuantity,
                        SaleReturnQuantity = saleReturnQuantity,
                        CurrentStock = currentStock,
                        BelowSafetyStock = belowSafetyStock
                    });
                }
                
                return new RestfulResult<List<JxStockInfo>>()
                {
                    Data = stockList,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<List<JxStockInfo>>()
                {
                    Code = 0,
                    Message = "查询失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 根据商品编码查询库存
        /// </summary>
        /// <param name="goodsCode"></param>
        /// <returns></returns>
        public async Task<RestfulResult<JxStockInfo>> GetStockByGoodsCodeAsync(string goodsCode)
        {
            try
            {
                // 获取商品信息
                var goods = await _goodsRepository.AsQueryable().Where(x => x.Code == goodsCode).FirstAsync();
                if (goods == null)
                {
                    return new RestfulResult<JxStockInfo>()
                    {
                        Code = 0,
                        Message = "商品不存在"
                    };
                }
                
                // 计算进货数量
                var purchaseQuantity = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "Purchase");
                // 计算进退货数量
                var purchaseReturnQuantity = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "PurchaseReturn");
                // 计算销货数量
                var saleQuantity = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "Sale");
                // 计算销退货数量
                var saleReturnQuantity = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "SaleReturn");
                
                // 计算当前库存
                var currentStock = purchaseQuantity - purchaseReturnQuantity - saleQuantity + saleReturnQuantity;
                
                // 判断是否低于安全库存
                bool belowSafetyStock = goods.SafeQty > 0 && currentStock < goods.SafeQty;
                
                var stockInfo = new JxStockInfo
                {
                    GoodsCode = Convert.ToString(goods.Code),
                    GoodsName = goods.Name,
                    GoodsCategory = goods.Category,
                    Specifications = goods.Model,
                    Origin = goods.Producer,
                    Unit = goods.Unit,
                    SafetyStock = goods.SafeQty ?? 0,
                    PurchaseQuantity = purchaseQuantity,
                    PurchaseReturnQuantity = purchaseReturnQuantity,
                    SaleQuantity = saleQuantity,
                    SaleReturnQuantity = saleReturnQuantity,
                    CurrentStock = currentStock,
                    BelowSafetyStock = belowSafetyStock
                };
                
                return new RestfulResult<JxStockInfo>()
                {
                    Data = stockInfo,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<JxStockInfo>()
                {
                    Code = 0,
                    Message = "查询失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 查询商品库存（分页）
        /// </summary>
        /// <param name="pageNo"></param>
        /// <param name="pageSize"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task<PageResult<InventoryInfo>> QueryInventoriesAsync(int pageNo, int pageSize, string keyword = null)
        {
            try
            {
                // 查询所有商品
                var goodsQuery = _goodsRepository.AsQueryable();

                // 添加关键字搜索
                if (!string.IsNullOrEmpty(keyword))
                {
                    goodsQuery = goodsQuery.Where(x => 
                        x.Code.Contains(keyword) || 
                        x.Name.Contains(keyword) || 
                        x.Model.Contains(keyword));
                }

                // 分页查询商品
                var goodsPage = await goodsQuery.ToPageAsync(pageNo, pageSize);

                // 计算每个商品的库存信息
                var inventoryList = new List<InventoryInfo>();
                // 由于无法直接使用ToList()方法，我们需要调整查询方式
                // 注意：这可能需要重新设计查询逻辑
                var allGoods = await _goodsRepository.AsQueryable()
                    .ToListAsync();
                foreach (var goods in allGoods)
                {
                    // 计算进货数量
                    var importQty = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "Purchase");
                    // 计算进退货数量
                    var importReturnQty = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "PurchaseReturn");
                    // 计算销货数量
                    var exportQty = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "Sale");
                    // 计算销退货数量
                    var exportReturnQty = await CalculateBillQuantityAsync(Convert.ToString(goods.Code), "SaleReturn");

                    // 计算当前库存
                    var currentStock = importQty - importReturnQty - exportQty + exportReturnQty;

                    string codeStr = Convert.ToString(goods.Code);
                    inventoryList.Add(new InventoryInfo
                    {
                        Id = goods.Id,
                        Code = codeStr,
                        Name = goods.Name,
                        Category = goods.Category,
                        Model = goods.Model,
                        Producer = goods.Producer,
                        Unit = goods.Unit,
                        BuyPrice = goods.BuyPrice,
                        SalePrice = goods.SalePrice,
                        SafeQty = goods.SafeQty,
                        ImportQty = importQty,
                        ImportReturnQty = importReturnQty,
                        ExportQty = exportQty,
                        ExportReturnQty = exportReturnQty,
                        InventoryQty = currentStock
                    });
                }

                // 使用List来存储结果，避免PageResult构造问题
                var resultList = inventoryList.Skip((pageNo - 1) * pageSize).Take(pageSize).ToList();
                // 由于PageResult的具体实现不清楚，我们暂时返回一个RestfulResult包装List
                // 注意：这可能需要接口调整
                throw new NotImplementedException("需要调整接口返回类型，PageResult的实现不清楚");
            }
            catch (Exception ex)
            {
                throw new Exception("查询库存失败: " + ex.Message);
            }
        }

        /// <summary>
        /// 检查库存是否充足
        /// </summary>
        /// <param name="goodsCode"></param>
        /// <param name="requiredQuantity"></param>
        /// <returns></returns>
        public async Task<RestfulResult<object>> CheckStockAsync(string goodsCode, int requiredQuantity)
        {
            try
            {
                var stockInfo = await GetStockByGoodsCodeAsync(goodsCode);
                // 检查stockInfo是否有效
                if (stockInfo == null || stockInfo.Data == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "获取库存信息失败"
                    };
                }
                
                if (stockInfo.Data.CurrentStock < requiredQuantity)
                {
                    return new RestfulResult<object>()
                    {
                        Data = false,
                        Code = 0,
                        Message = string.Format("库存不足: 商品{0}，当前库存{1}", goodsCode, stockInfo.Data.CurrentStock)
                    };
                }
                
                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "库存充足"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "检查库存失败: " + ex.Message
                };
            }
        }
    }

    /// <summary>
    /// 库存信息
    /// </summary>
    public class JxStockInfo
    {
        /// <summary>
        /// 商品编码
        /// </summary>
        public string? GoodsCode { get; set; }
        
        /// <summary>
        /// 商品名称
        /// </summary>
        public string? GoodsName { get; set; }
        
        /// <summary>
        /// 商品类别
        /// </summary>
        public string? GoodsCategory { get; set; }
        
        /// <summary>
        /// 规格型号
        /// </summary>
        public string? Specifications { get; set; }
        
        /// <summary>
        /// 产地
        /// </summary>
        public string? Origin { get; set; }
        
        /// <summary>
        /// 计量单位
        /// </summary>
        public string? Unit { get; set; }
        
        /// <summary>
        /// 安全库存
        /// </summary>
        public int SafetyStock { get; set; }
        
        /// <summary>
        /// 进货数量
        /// </summary>
        public int PurchaseQuantity { get; set; }
        
        /// <summary>
        /// 进退货数量
        /// </summary>
        public int PurchaseReturnQuantity { get; set; }
        
        /// <summary>
        /// 销货数量
        /// </summary>
        public int SaleQuantity { get; set; }
        
        /// <summary>
        /// 销退货数量
        /// </summary>
        public int SaleReturnQuantity { get; set; }
        
        /// <summary>
        /// 当前库存
        /// </summary>
        public int CurrentStock { get; set; }
        
        /// <summary>
        /// 是否低于安全库存
        /// </summary>
        public bool BelowSafetyStock { get; set; }
    }
}